<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2017 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 李邦琦 <1536549251@qq.com>
// +----------------------------------------------------------------------

namespace app\crm\model;
use think\Db;
use think\Model;
use think\Cache;
use think\Loader;

class Recovery extends Model
{

    public function reductionCustomer ($where)
    {
        $result = Db::name('vip_customer_basic')->field('customer_code, old_user')->where($where)->select();
        foreach ($result as $val) {
            $data = array(
                'create_user' => $val['old_user'],
                'distribution_time' => date('Y-m-d H:i:s'),
                'recovery' => 1,
                'old_user' => null,
                'recycle_user' => null,
                'recycle_time' => null,
            );
            $res[] = Db::name('vip_customer_basic')->where('customer_code="'.$val['customer_code'].'"')->update($data);
        }
        if ($res){
            echo json_encode(array('success'=>true,'msg'=>'还原成功！'));
        } else {
            echo json_encode(array('msg'=>'还原失败！'));
        }
    }


    /**
     * 新增数据任务客户
     * @param  array $data 新增数据
     * @return json        新增结果
     */
    public function addDataTask ($data)
    {
        // 添加前 该客户资料是否存在任务中
        $res = Db::name('vip_customer_basic')->field('data_task, task_id')->where('customer_code="'.$data['customer_code'].'"')->find();
        if ($res['data_task']) {
            // $result = Db::name('vip_data_customer')->where('customer_code="'.$data['customer_code'].'" AND data_task="'.$data['data_task'].'"')->update($data);
            echo json_encode(array('msg'=>'添加失败，该客户资料已存在数据任务 '.$res['data_task'].' 中！'));
            exit;
        } elseif ($res['task_id']) {
            echo json_encode(array('msg'=>'添加失败，该客户资料已存在回访任务 '.$res['task_id'].' 中！'));
            exit;
        } else {
            $result = Db::name('vip_data_customer')->insert($data);
        }

        if ($result) {
            $update = array(
                'data_task'=>$data['data_task'],
                'create_user' => $data['username'],
                'recovery'=>1,
                'old_user' => null,
                'recycle_user' => null,
                'recycle_time' => null,
            );
            Db::name('vip_customer_basic')->where('customer_code="'.$data['customer_code'].'"')->update($update);
            echo json_encode(array('success'=>true,'msg'=>'添加成功！'));
        } else {
            echo json_encode(array('msg'=>'添加失败！'));
        }
    }


}